package com.mybatisplus.mp.redisson;

import org.redisson.api.RCountDownLatch;
import org.redisson.api.RLock;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.print.attribute.SupportedValuesAttribute;
import java.util.ArrayList;
import java.util.List;

@RestController
public class RedissonController {
    @Autowired
    private RedissonClient client;

    @GetMapping("/redisson")
    public String get() {
        //获取一把锁，只要锁名字一样就是同一把锁
        RLock lock = client.getLock("my-lock");
        // 1.锁自动续期，默认30s，运行期间自动给锁再加30s
        // 2.加锁业务只要运行完成，就不会给锁续期，即使不手动解锁，默认30s后自动删除
        lock.lock();//阻塞式等待
        try {
            System.out.println("业务执行:" + Thread.currentThread().getName());
            Thread.sleep(10000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            System.out.println("释放锁：" + Thread.currentThread().getName());
            lock.unlock();
        }
        return "hello";
    }

    /**
     * 闭锁测试1
     */
    @GetMapping("/lock")
    public String lookDoor() throws InterruptedException {
        RCountDownLatch door = client.getCountDownLatch("door");
        door.trySetCount(5L);
        door.await();// 等待闭锁都完成
        return "锁门成功";
    }

    /**
     * 闭锁测试2
     */
    @GetMapping("gogogo/{id}")
    public String gogogo(@PathVariable("id") int id) {
        List<SupportedValuesAttribute> list = new ArrayList();
        RCountDownLatch door = client.getCountDownLatch("door");
        door.countDown();//锁计数减一
        return "gogogo";
    }

    /**
     * 信号量测试1
     */
    @GetMapping("/park")
    public String park() throws InterruptedException {
        RSemaphore park = client.getSemaphore("park");
        park.acquire();//获取一个信号量,如果没有位置则进行等待
//        boolean b = park.tryAcquire();//获取一个信号量，获取则返回true,不等待
        return "停车";
    }

    /**
     * 信号量测试2
     */
    @GetMapping("/go")
    public String leave() {
        RSemaphore park = client.getSemaphore("park");
        park.release();
        return "离开";
    }
}
